package mammuthus.controller

import net.csdn.modules.http.{ViewType, RestRequest, ApplicationController}
import net.csdn.annotation.rest.{State, BasicInfo, At}
import com.google.inject.Inject
import mammuthus.master.Master
import net.liftweb.{json => SJSon}
import org.apache.commons.fileupload.servlet.ServletFileUpload
import org.apache.commons.fileupload.disk.DiskFileItemFactory
import net.csdn.common.reflect.ReflectHelper
import javax.servlet.http.HttpServletRequest
import org.apache.commons.io.{IOUtils, FileUtils, FilenameUtils}
import java.io.{FileOutputStream, File}
import net.csdn.common.env.Environment
import mammuthus.controller.filter.TokenAuthFilter

/**
 * 2/2/15 WilliamZhu(allwefantasy@gmail.com)
 */
class UploadDownloadTaskController @Inject()(akkaMaster: Master) extends ApplicationController with TokenAuthFilter {

  implicit val formats = SJSon.Serialization.formats(SJSon.NoTypeHints)

  @At(path = Array("/download"), types = Array(RestRequest.Method.GET, RestRequest.Method.POST))
  @BasicInfo(
    desc = "可指定哪些服务器下载指定url地址的文件到指定目录",
    state = State.alpha,
    testParams = "?slaves=allwefantasy&url=http://127.0.0.1:9003/test.tar.gz&filePath=/tmp/jack3.tar.gz",
    testResult = "task submit",
    author = "WilliamZhu",
    email = "allwefantasy@gmail.com"
  )
  def download = {
    auth
    akkaMaster.download(param("slaves", "pool-01"), param("url", ""), param("filePath", ""))
    render("task submit")
  }

  @At(path = Array("/block/download"), types = Array(RestRequest.Method.GET, RestRequest.Method.POST))
  @BasicInfo(
    desc = "可指定哪些服务器下载指定url地址的文件到指定目录",
    state = State.alpha,
    testParams = "?slaves=allwefantasy&url=http://127.0.0.1:9003/test.tar.gz&filePath=/tmp/jack3.tar.gz",
    testResult = "task submit",
    author = "WilliamZhu",
    email = "allwefantasy@gmail.com"
  )
  def blockDownload = {
    auth

    implicit val formats = SJSon.Serialization.formats(SJSon.NoTypeHints)
    val res = akkaMaster.blockDownload(param("slaves", "pool-01"), param("url", ""), param("filePath", ""))
    render(SJSon.Serialization.write(res), ViewType.json)
  }

  @At(path = Array("/upload"), types = Array(RestRequest.Method.GET, RestRequest.Method.POST))
  @BasicInfo(
    desc = "可指定哪些服务器下载指定url地址的文件到指定目录",
    state = State.alpha,
    testParams = "",
    testResult = "task submit",
    author = "WilliamZhu",
    email = "allwefantasy@gmail.com"
  )
  def upload = {
    auth
    println(request.contentAsString())

    val fileName = param("fileName", "")
    if (!fileName.isEmpty) {
      val env = new Environment(akkaMaster._conf)
      logger.info("upload file {}", fileName)
      IOUtils.write(request.contentByteArray(), new FileOutputStream(new File(env.templateDirFile().getPath + "/assets/" + fileName)))

    }

    //    val items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(ReflectHelper.field(request, "servletRequest").asInstanceOf[HttpServletRequest])
    //    try {
    //      items.filterNot(f => f.isFormField).map {
    //        item =>
    //        //val fieldName = item.getFieldName();
    //          val fileName = FilenameUtils.getName(item.getName())
    //          val fileContent = item.getInputStream()
    //          val env = new Environment(akkaMaster._conf)
    //          val targetPath =  new File(env.templateDirFile().getPath + "/assets/" + fileName)
    //          logger.info(s"upload to ${targetPath.getPath}")
    //          FileUtils.copyInputStreamToFile(fileContent,targetPath)
    //      }
    //    } catch {
    //      case e: Exception =>
    //        logger.info("upload fail ", e)
    //        render(500, s"upload fail,check master log ${e.getMessage}")
    //    }
    render("upload success")
  }

  @At(path = Array("/upload2"), types = Array(RestRequest.Method.GET, RestRequest.Method.POST))
  @BasicInfo(
    desc = "可指定哪些服务器下载指定url地址的文件到指定目录",
    state = State.alpha,
    testParams = "",
    testResult = "task submit",
    author = "WilliamZhu",
    email = "allwefantasy@gmail.com"
  )
  def upload2 = {
    auth
    import scala.collection.JavaConversions._
    val items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(ReflectHelper.field(request, "servletRequest").asInstanceOf[HttpServletRequest])
    try {
      logger.info(items+"")
      items.map {
        item =>
        //val fieldName = item.getFieldName();
          val fileName = FilenameUtils.getName(item.getName())
          val fileContent = item.getInputStream()
          val env = new Environment(akkaMaster._conf)
          val targetPath = new File(env.templateDirFile().getPath + "/assets/" + fileName)
          logger.info(s"upload to ${targetPath.getPath}")
          FileUtils.copyInputStreamToFile(fileContent, targetPath)
      }
    } catch {
      case e: Exception =>
        logger.info("upload fail ", e)
        render(500, s"upload fail,check master log ${e.getMessage}")
    }
    render("upload success")
  }

}
